<template>
    <div class="fixed-asset-inventory">
        <div class="content">
            <div class="header-actions">
                <router-link to="/main/xingzheng/gudingzichan"><el-button>返回</el-button></router-link>
                <div class="button-group" v-if="!isViewMode">
                    <el-button type="primary" @click="addRow">新增资产项</el-button>
                    <el-button type="danger" @click="deleteSelectedRows">删除选中</el-button>
                    <el-button type="success" @click="saveData">保存</el-button>
                    <router-link
                            to="/main/xingzheng/gudingzichan/gdzcpandian-list"><el-button>列表</el-button></router-link>
                </div>
            </div>
            <h2 class="title">固定资产盘点表</h2>
            <el-table :data="inventoryList" border style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" v-if="!isViewMode" />
                <el-table-column type="index" label="序号" width="50" />
                <el-table-column prop="assetCode" label="资产编号" width="120">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.assetCode" placeholder="请输入资产编号" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="assetName" label="资产名称" width="120">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.assetName" placeholder="请输入资产名称" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="specification" label="规格型号" width="120">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.specification" placeholder="请输入规格型号" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="purchaseDate" label="购入日期" width="250">
                    <template v-slot="scope">
                        <el-date-picker v-model="scope.row.purchaseDate" type="date" placeholder="选择日期"
                            :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="120">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.unit" placeholder="请输入单位" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="initialCount" label="初盘数" width="220">
                    <template v-slot="scope">
                        <el-input-number v-model="scope.row.initialCount" :min="0" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="recheckCount" label="复盘数量" width="220">
                    <template v-slot="scope">
                        <el-input-number v-model="scope.row.recheckCount" :min="0" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="sampleCount" label="抽盘数量" width="220">
                    <template v-slot="scope">
                        <el-input-number v-model="scope.row.sampleCount" :min="0" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="originalPrice" label="原价" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.originalPrice" placeholder="请输入原价" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="accumulatedDepreciation" label="累计折旧" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.accumulatedDepreciation" placeholder="请输入累计折旧"
                            :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="netValue" label="净值" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.netValue" placeholder="请输入净值" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="department" label="所属部门" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.department" placeholder="请输入所属部门" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="storageLocation" label="存放位置" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.storageLocation" placeholder="请输入存放位置" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="responsiblePerson" label="管理责任人" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.responsiblePerson" placeholder="请输入管理责任人" :disabled="isViewMode" />
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" width="150">
                    <template v-slot="scope">
                        <el-input v-model="scope.row.remarks" placeholder="请输入备注" :disabled="isViewMode" />
                    </template>
                </el-table-column>
            </el-table>
            <p class="note">注:本表中:原价、累计折旧、净值由财务管理部会计填写。</p>
            <div class="signature-group">
                <el-form :inline="true">
                    <el-form-item label="审核:">
                        <el-input style="width: 90%;" v-model="reviewer" :disabled="isViewMode" />
                    </el-form-item>
                    <el-form-item label="确认:">
                        <el-input style="width: 90%;" v-model="confirmer" :disabled="isViewMode" />
                    </el-form-item>
                    <el-form-item label="抽盘人:">
                        <el-input style="width: 90%;" v-model="sampler" :disabled="isViewMode" />
                    </el-form-item>
                    <el-form-item label="复盘人:">
                        <el-input style="width: 90%;" v-model="rechecker" :disabled="isViewMode" />
                    </el-form-item>
                    <el-form-item label="初盘人:">
                        <el-input style="width: 90%;" v-model="initialChecker" :disabled="isViewMode" />
                    </el-form-item>
                </el-form>
            </div>
            <p class="save-period">保存期限：长期</p>
        </div>
    </div>
</template>

<script>
import { saveFixedAssetInventory, getFixedAssetInventoryDetail, updateFixedAssetInventory } from '@/api/fixedAssetInventory'

export default {
    data() {
        return {
            inventoryList: [this.getEmptyRow()],
            selectedRows: [],
            reviewer: '',
            confirmer: '',
            sampler: '',
            rechecker: '',
            initialChecker: '',
            isViewMode: false,
            id: null
        }
    },
    created() {
        // 从路由参数获取 id 和模式
        const { id, mode } = this.$route.query;
        this.id = id;
        this.isViewMode = mode === 'view';

        // 如果有 id，加载数据
        if (id) {
            this.loadData(id);
        }
    },
    methods: {
        getEmptyRow() {
            return {
                // 新增一个唯一的 id，使用 Date.now() 生成简单的唯一标识
                // id: Date.now(),
                assetCode: '',
                assetName: '',
                specification: '',
                purchaseDate: '',
                unit: '',
                initialCount: 0,
                recheckCount: 0,
                sampleCount: 0,
                originalPrice: '',
                accumulatedDepreciation: '',
                netValue: '',
                department: '',
                storageLocation: '',
                responsiblePerson: '',
                remarks: ''
            }
        },
        async loadData(id) {
            try {
                const response = await getFixedAssetInventoryDetail(id);
                if (response.data) {
                    const data = response.data;
                    // 确保保留记录的ID
                    this.inventoryList = [{
                        ...data,
                        id: data.id  // 明确保留ID
                    }];
                    this.reviewer = data.reviewer || '';
                    this.confirmer = data.confirmer || '';
                    this.sampler = data.sampler || '';
                    this.rechecker = data.rechecker || '';
                    this.initialChecker = data.initialChecker || '';
                }
            } catch (error) {
                this.$message.error('获取数据失败：' + error.message);
            }
        },
        addRow() {
            this.inventoryList.push(this.getEmptyRow());
        },
        handleSelectionChange(val) {
            this.selectedRows = val;
        },
        deleteSelectedRows() {
            if (this.selectedRows.length === 0) {
                this.$message.warning('请选择要删除的行');
                return;
            }
            this.$confirm('确定要删除选中的行吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const selectedIds = this.selectedRows.map(row => row.id);
                // 过滤掉选中的行，保留未选中的行
                this.inventoryList = this.inventoryList.filter(item => !selectedIds.includes(item.id));
                this.$message.success('删除成功');
            }).catch(() => { });
        },
        async saveData() {
            try {
                if (this.inventoryList.length === 0) {
                    throw new Error('请至少添加一条记录');
                }
                if (!this.reviewer) throw new Error('请填写审核人');
                if (!this.confirmer) throw new Error('请填写确认人');
                if (!this.sampler) throw new Error('请填写抽盘人');
                if (!this.rechecker) throw new Error('请填写复盘人');
                if (!this.initialChecker) throw new Error('请填写初盘人');

                const processedList = this.inventoryList.map(item => ({
                    ...item,
                    initialCount: Number(item.initialCount || 0),
                    recheckCount: Number(item.recheckCount || 0),
                    sampleCount: Number(item.sampleCount || 0),
                    originalPrice: Number(item.originalPrice || 0),
                    accumulatedDepreciation: Number(item.accumulatedDepreciation || 0),
                    netValue: Number(item.netValue || 0),
                    purchaseDate: item.purchaseDate ? this.formatDate(item.purchaseDate) : null
                }));

                // 构建请求参数
                const params = {
                    inventoryList: processedList,
                    reviewer: this.reviewer,
                    confirmer: this.confirmer,
                    sampler: this.sampler,
                    rechecker: this.rechecker,
                    initialChecker: this.initialChecker
                };

                // 如果有ID，添加到params中
                if (this.id) {
                    params.id = this.id;
                }

                // 统一使用save接口
                await saveFixedAssetInventory(params);
                this.$message.success(this.id ? '更新成功' : '新增成功');

                this.$router.push('/main/xingzheng/gudingzichan/gdzcpandian-list');
            } catch (error) {
                this.$message.error('保存失败：' + error.message);
            }
        },
        formatDate(date) {
            if (!date) return null;
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
    }
}
</script>

<style scoped>
.fixed-asset-inventory {
    font-family: '宋体', sans-serif;
    /* padding: 20px; */
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    height: calc(100vh);
}

.content {
    width: 1200px;
    margin: 0 auto;
    background-color: #f9f9f9;
    padding: 20px;
    height: calc(100vh - 40px);
}

.header-actions {
    display: flex;
    gap: 20px;
    justify-content: space-between;
}

::v-deep .el-form-item__label {
    padding: 0px;
}

.title {
    text-align: center;
    color: #333;
    /* margin-bottom: 20px; */
}

.button-group {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

.el-button {
    border-radius: 4px;
}

.el-table {
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    max-height: 250px;
    overflow-y: auto;
}

.el-table th {
    background-color: #f2f2f2;
    color: #333;
}

.el-table td {
    border-bottom: 1px solid #ddd;
}

.note {
    color: #666;
    margin: 20px 0px;
}

.signature-group {
    margin: 20px 0;
    display: flex;
    gap: 20px;
    align-items: center;
    white-space: nowrap;
}

.el-form-item {
    margin-bottom: 0;
}

.save-period {
    color: #666;
    margin-top: 20px;
}
</style>